<template>
  <!--系统管理/短信模板配置-组件 -->
  <section class="component case-approval-common">
    <el-form :model="listQuery" :rules="rules" label-width="100px" ref="form" :disabled="type === 'see'">
      <el-row>
        <el-col :span="8">
          <el-form-item label="模板代码" prop="templateCode">
            <el-input v-model.trim="listQuery.templateCode" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model.trim="listQuery.templateName" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板状态" prop="archive">
            <el-select v-model="listQuery.archive" @change="ch_Status" class="message-select" clearable>
              <el-option label="启用" value="0"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="逾期期数" prop="overdueStage">
            <!-- <el-select v-model="listQuery.overdueStage" class="message-select" multiple collapse-tags> -->
              <!-- 此处collapse-tags为element-ui中el-select的属性，此处需去掉，否则会在选项后自动累加 -->
            <el-select v-model="listQuery.overdueStage" class="message-select" multiple>
              <el-option v-for="{ index, code, name } in $dict.getDictData(
                  'OverduePeriodStatus'
                )" :key="index" :label="name" :value="code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="选择短信变量">
            <el-select v-model="listQuery.messageVariableType" @change="getValueBtn" class="message-select">
              <el-option v-for="{ index, code, name } in $dict.getDictData(
                  'MessageVariableType'
                )" :key="index" :label="name" :value="code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="模板内容" prop="templateContent">
            <el-input v-model.trim="listQuery.templateContent" type="textarea" @input="change($event)" :maxlength="300" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="confirm-button">
      <el-button @click="close()">{{type !== 'see' ? '取消' : '关闭'}}</el-button>
      <el-button @click="saveBtn('listQuery')" v-if="type !== 'see'">保存</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { UserService } from "~/services/management-service/user.service";
import { Form } from "element-ui";

@Component({})
export default class CaseApprovalCommon extends Vue {
  public $refs: { form: Form };
  @Dependencies(UserService)
  private userService: UserService;
  
  private listQuery: any = {
    templateCode: "",
    templateName: "",
    archive: "",
    overdueStage: "",
    messageVariableType: "",
    templateContent: ""
  };
  private rules: any = {
    templateCode: [
      { required: true, message: "请输入模板代码", trigger: "blur" },
      { pattern: /^[A-Za-z0-9]+$/, message: "请输入英文字母或数字", trigger: "blur" }
    ],
    templateName: [
      { required: true, message: "请输入模板名称", trigger: "blur" }
    ],
    archive: [{ required: true, message: "请选择模板状态", trigger: 'blur' }],
    overdueStage: [
      { required: true, message: "请选择逾期阶段", trigger: 'blur' }
    ],
    messageVariableType: [
      { required: true, message: "请选择短信变量", trigger: "blur" }
    ],
    templateContent: [
      { required: true, message: "请输入模板内容", trigger: "blur" },
    ]
  };
  @Prop() private num: any;
  @Prop() private tableRow: any;
  @Prop({ required: true }) private type: string;
  private textBox: any = ""

  @Emit("close") private close () {
    this.listQuery = {};
    this.reset();
  }
  @Watch("tableRow")
  private ontableRowChange () {
    this.listQuery = this.tableRow;
    if(this.listQuery.overdueStage){
      const splDueStage = this.tableRow.overdueStage.toString()
      this.listQuery.overdueStage = splDueStage.split(",")
    }
  }

  private mounted () {
    this.listQuery = this.tableRow;
    console.log("this.listQuery", this.listQuery)
    if(this.tableRow.overdueStage){
      // this.listQuery.overdueStage = this.tableRow.overdueStage.split(",")
      const splDueStage = this.tableRow.overdueStage.toString()
      this.listQuery.overdueStage = splDueStage.split(",")
    }
  }

  private ch_Status () {
    this.$forceUpdate()
  }

  private reset () {
    const form: any = this.$refs["form"];
    form.resetFields();
  }

  private getValueBtn () {
    if (this.listQuery.templateContent === undefined) { this.listQuery.templateContent = '' }
    this.textBox = this.listQuery.messageVariableType
    const textConData = this.listQuery.templateContent + this.replaceData(this.textBox)
    this.listQuery.templateContent = textConData
  }

  private replaceData (data) {
    let state = ""
    switch (data) {
      case "RELATION_NAME":
        state = "$" + "{relationName}"; // 姓名
        break;
      case "PERSONAL_NAME":
        state = "$" + "{personalName}"; // 客户名称
        break;
      case "GENDER":
        state = "$" + "{gender}"; // 先生/女士
        break;
      case "APPELLATION":
        state = "$" + "{appellation}"; // 称谓
        break;
      case "INSERTTIME":
        state = "$" + "{insertTime}"; // 逾期统计日
        break;
      case "PRODUCTNAME":
        state = "$" + "{productName}"; // 产品名称
        break;
      case "OVERDUEDAYS":
        state = "$" + "{overdueDays}";  // 逾期天数
        break;
      case "OVERDUEAMOUNT":
        state = "$" + "{overdueAmount}"; // 逾期金额
        break;
      case "CASEMONEY":
        state = "$" + "{caseMoney}"; // 账户总金额
        break;
      case "HANDPHONE":
        state = "$" + "{handPhone}"; // 经办电话
        break;
      case "DEFAULTCARDNUMBER":
        state = "$" + "{deductionCardNumber}"; // 默认扣款卡号后四位
        break;
      case "REPLACECARDNUMBER":
        state = "$" + "{replaceCardNumber}"; // 代还卡号
        break;
      case "CUSTOMERTELPHONE":
        state = "$" + "{customerTelphone}"; // 客服电话
        break;
      case "PREPAYDATE":
        state = "$" + "{prePayDate}"; // 上一个还款日
        break;
    }
    return state;
  }

  private change (e) {
    this.$forceUpdate()
  }

  private validateTemplateContent(rule, value, callback) {
    if (!/^$.*}$/.test(value)) {
       callback(new Error("请输入正确的模板内容"));
    }
  }

  private async saveBtn (listQuery) {
    // const result = await this.$refs.form
    //   .validate()
    //   .then(() => true)
    //   .catch(() => false);
    const result: any = this.$refs["form"];
    if (!result) return;
    // this.listQuery.overdueStages = this.listQuery.overdueStage
    if (this.num === 'add') {
      this.addBtn()
    } else {
      this.editBtn()
    }
  }

  private paramsHandler () {
    // 查询条件
    const params = { ...this.listQuery };
    params.overdueStages = this.listQuery.overdueStage;
    delete params.overdueStage;
    return params;
  }

  private addBtn () {
    this.userService.addSmsTemplateInfo(this.paramsHandler()).subscribe(
      data => {
        this.$message.success("操作成功");
        this.close();
      },
      err => {
        this.close();
      }
    );
  }
  private editBtn () {
    this.userService.updateSmsTemplateInfo(this.paramsHandler()).subscribe(data => {
      const form: any = this.$refs["form"];
      form.resetFields();
      this.$emit("close");
      this.$message.success("保存成功!");
    });
  }
}
</script>

<style lang="less" scoped></style>
<style lang="less">
/*deep*/
.message-select {
  width: 100% !important;
  .el-input {
    width: 100% !important;
  }
}
.component.case-approval-common {
  .data-box > * {
    padding: 0 !important;
  }
}
</style>
